package com.example.demo.controller;

import com.example.demo.entity.Tem;
import com.example.demo.utils.ExcuteLinux;
import com.example.demo.utils.ValidatorUtil;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/start")
@RestController
public class SimulationController {

    @Value("${file.start.dir}")
    private String starDir;

    //文件名校验
    private ValidatorUtil validatorUtil;

    //执行linux命令
    private ExcuteLinux excuteLinux;

    @PostMapping("/simulation2")
    public String startSimulation(@RequestParam("username") String username, @RequestParam("time") String time)throws Exception{
        JSONObject result = new JSONObject();
        String fileName = username+"_"+time;

        if(validatorUtil.isValid(fileName)) {
            excuteLinux.exeCmd("cd "+ starDir + " && mkdir " + fileName);
        }else{
            result.put("error","新建文件夹名不合法,请重新输入");
        }
        result.put("success","成功开启仿真");
        return result.toString();
    }



    @PostMapping("/simulation")
    //@ResponseBody
    public String startSimulation(@RequestBody Tem user)throws Exception{

        JSONObject result = new JSONObject();
        String fileName = user.getUsername()+"_"+user.getTime();

        if(validatorUtil.isValid(fileName)) {
            excuteLinux.exeCmd("cd "+ starDir + " && mkdir " + fileName);
        }else{
            result.put("error","新建文件夹名不合法,请重新输入");
        }
        result.put("success","成功开启仿真");
        return result.toString();
    }

    @PostMapping("/break")
    public String breakSimulation(@RequestBody Tem user){
        JSONObject result = new JSONObject();
        String fileName = user.getUsername()+"_"+user.getTime();

//        excuteLinux.exeCmd("ps -ef | grep "+fileName+" | awk '{print $2}' | xargs kill -9");
        excuteLinux.exeCmd("cd /home/unicom/tongyijiemian/java_sub6G/Sub6G/ && rm -rf " + fileName);
        System.out.println(fileName+"仿真已终止");
        try {
            result.put("success","仿真终止");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}
